package org.destiny.swing.mapping.base;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;

import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class RadioButtonGroupMapper extends AbstractFormItemMapper<Enum<?>> {
	private JPanel radioButtonPane;
	private ButtonGroup buttonGroup;

	public RadioButtonGroupMapper(Field field, Object model) {
		super(field);
		this.model = model;
		radioButtonPane = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
		buttonGroup = new ButtonGroup();
		JRadioButton radioButton;
		for (Object enObj : fieldType.getEnumConstants()) {
			Enum<?> en = (Enum<?>) enObj;
			radioButton = new JRadioButton(en.toString());
			radioButtonPane.add(radioButton);
			buttonGroup.add(radioButton);
		}
	}

	@Override
	public JComponent getInputComponent() {
		return radioButtonPane;
	}


	class EnumButton implements ActionListener {
		Enum<?> enumValue;
		JRadioButton radioButton;

		public EnumButton(Enum<?> enumValue, JRadioButton radioButton) {
			this.enumValue = enumValue;
			this.radioButton = radioButton;
			this.radioButton.addActionListener(this);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			if (radioButton.isSelected() && fieldValue != this.enumValue) {
				setFieldValue(this.enumValue);
			}
		}

	}

}
